import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { CoreModule } from './../core.module';
import { NzNotificationService, NzMessageService } from 'ng-zorro-antd';
import { timeout } from 'rxjs/operators';
import { urlService } from './url';

@Injectable({
  providedIn: CoreModule
})
export class ApiService {

  constructor(
    private message: NzMessageService, // lee 添加
    private http: HttpClient,
    private notification: NzNotificationService
  ) { }
  environment() {
    return {
      hospital: 'http://' + window.location.hostname + ':4201',
      pharmacy: 'http://' + window.location.hostname + ':4202',
      medical: 'http://' + window.location.hostname + ':4200'
    };
  }
  get(url: string, params?: { [key: string]: any }, noFail?: Boolean): Promise<Function> {
     const request = this.http.get(urlService('dev', url), {
      params: params
    })
    .pipe(timeout(240000))
    .toPromise();
    return new Promise((resolve, reject) => {
      request.then((res: any) => {
        if (res.data.status === '0') {
          resolve(res.data);
        } else {
          reject(res.data);
          if (!noFail) {
            this.message.error(res.data.message);
          }
        }
      }).catch(res => {
        console.log(res);
        if(res.status === 403){
          window.location.href = this.environment().medical;
        } else {
          this.notification.create('error', '未知错误，请联系管理员', '错误提示');
        }
      });
    });
  }
  post(url: string, data?: { [key: string]: any }, params?: { [key: string]: any }, noFail?: Boolean): Promise<Function> {
    const request = this.http.post(urlService('dev', url), data, {
     params: params
   })
   .pipe(timeout(60000))
   .toPromise();
   return new Promise((resolve, reject) => {
     request.then((res: any) => {
       console.log(res);
       if (res.status === '0') {
         resolve(res);
       } else {
         reject(res);
         if (!noFail) {
           this.message.error(res.message);
         }
       }
     }).catch(res => {
      console.log(res);
      if(res.status === 403){
        window.location.href = this.environment().medical;
      } else {
        this.notification.create('error', '未知错误，请联系管理员', '错误提示');
      }
     });
   });
 }
}
